package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Title: UserController
 * @Package com.itheima.reggie.controller
 * @Author: 🐟
 * @Copyright 🐟
 * @CreateTime: 2022/9/15 19:29
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sengMsg(@RequestBody User user, HttpServletRequest request) {
        System.out.println(user.getPhone());
        String msg = userService.sendmsg(user.getPhone());
        //将验证码存入SESSION中
       // request.getSession().setAttribute("key", msg);
        //将验证码存入Redis中
        String phone = user.getPhone();
        redisTemplate.opsForValue().set(phone,msg,5, TimeUnit.MINUTES);

        return R.success("验证码发送成功");
    }

    @PostMapping("/login")
    public R<String> login(@RequestBody Map<String, String> jieshou, HttpServletRequest request) {
        //从SESSION中取出验证码
       // String key = (String) request.getSession().getAttribute("key");
        //将验证码从Redis中取出
         String phone = jieshou.get("phone");
        String key = (String) redisTemplate.opsForValue().get(phone);

        String code = jieshou.get("code");
        LambdaUpdateWrapper<User> lqw = new LambdaUpdateWrapper<>();
        lqw.eq(User::getPhone, phone);
        if (key.equals(code)) {
            redisTemplate.delete(phone);
            //验证通过
            int count = userService.count(lqw);
            if (count == 0) {
                //新用户
                User user = new User();
                user.setPhone(jieshou.get("phone"));
                userService.save(user);
                request.getSession().setAttribute("User", user.getId());
                return R.success("登录成功");
            } else {
                //老用户
                User one = userService.getOne(lqw);
                request.getSession().setAttribute("User", one.getId());
                return R.success("登录成功");
            }
        } else {
            //验证不通过
            return R.error("验证码错误");
        }
    }
    @PostMapping("/loginout")
    public R<String> loginout(HttpServletRequest request){
        request.getSession().removeAttribute("User");
        return R.success("退出成功");
    }
}
